package control;

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import model.bean.categoria;
import model.bean.livro;
import model.dao.LivroDao;

/**
 * Servlet implementation class ServletUsuario
 */
@WebServlet("/Livro")
public class ServletLivro extends HttpServlet {
	private static final long serialVersionUID = 1L;

	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public ServletLivro() {
		super();
		// TODO Auto-generated constructor stub
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		
		LivroDao dao = new LivroDao();
		livro obj = new livro();
		categoria obj1 = new categoria();
		obj1.setId(Integer.parseInt(request.getParameter("categoria")));
		
		String id = request.getParameter("id");
		obj.setNome(request.getParameter("nome"));
		obj.setDescricao(request.getParameter("descricao"));
		obj.setQtd(Integer.parseInt(request.getParameter("qtd")));
		obj.setCategoria(obj1);

		if (!id.equals("0") && id != null) {
			obj.setId(Integer.parseInt(id));

			int acao = Integer.parseInt(request.getParameter("acao"));
			if (acao > 0) {
				dao.delete(obj, Integer.parseInt(id));
			} else {
				dao.update(obj);
			}
		} else {
			dao.create(obj);
		}
		String urlRetorno = request.getHeader("referer");
		urlRetorno = urlRetorno.replace("?", ";");
		String[] urls = urlRetorno.contains(";") ? urlRetorno.split(";") : null;
		if(urls != null && urls.length > 0){
			response.sendRedirect(urls[0] + "?content=4");
		}else{
			response.sendRedirect(urlRetorno + "?content=4");
		}
	}
}
